using System;
using System.Collections.Generic;
using Microsoft.Win32;

namespace EasyPath_CSharp
{
    class RegistryUtils
    {

        private const string ENVIRONMENT_URL = "SYSTEM\\ControlSet001\\Control\\Session Manager\\Environment";

        private const string PATH_NAME = "Path";

        public static RegistryKey openKey()
        {
            RegistryKey key = Registry.LocalMachine;
            RegistryKey software = key.OpenSubKey(ENVIRONMENT_URL, true);

            return software;
        }

        /**
         * 遍历注册表目录下所有值
         */
        public static Dictionary<string, string> list()
        {
            
            RegistryKey software = openKey();

            Dictionary<string, string> keyValue = new Dictionary<string, string>();
            foreach (string key in software.GetValueNames())
            {
                string value = (string)software.GetValue(key, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
                if(string.IsNullOrEmpty(value))
                {
                    continue;
                }
                keyValue.Add(key, value);
                // Console.WriteLine("key: {0},value: {1}", key, value);
            }
            software.Dispose();

            return keyValue;
        }

        /**
         * 设置注册表值
         */
        public static void set(IDictionary<string, string> keyValue)
        {
            RegistryKey software = openKey();
            foreach (var kv in keyValue)
            {
                var key = kv.Key;
                RegistryValueKind kind = key.Contains("%") ? RegistryValueKind.ExpandString : RegistryValueKind.String;
                software.SetValue(key, kv.Value, kind);
            }

            software.Dispose();
        }

        /**
         * 删除注册表值
         */
        public static void remove(ICollection<string> keys)
        {
            RegistryKey software = openKey();

            //foreach (String key in keys)
            //{
            //    Console.WriteLine("remove key: {0}");
            //    // software.DeleteValue(key);
            //}
            software.Dispose();
        }
    }
}
